import { useEffect, useRef } from 'react'

export default function VideoPlayer({ src, isPlaying }) {
  const ref = useRef(null)

  useEffect(
    () => {
      // In React, rendering should be a pure calculation of JSX and should not
      // contain side effects like modifying the DOM. Moreover, when `VideoPlayer`
      // is called for the first time, its DOM does not exist yet! There isn't a
      // DOM node yet to call `play()` or `pause()` on, because React doesn't know
      // what DOM to create until you return the JSX.
      // The solution here is to wrap the side effect with `useEffect` to move it
      // out of the rendering calculation.
      if (isPlaying) {
        ref.current.play()
      } else {
        ref.current.pause()
      }
    },
    // The dependency array can contain multiple dependencies. React will only skip
    // re-running the `Effect` if all of the dependencies you specify have exactly
    // the same values as they had during the previous render. React compares the
    // dependency values using the `Object.is` comparison.
    //   - if no dependency, runs after every render
    //   - [], runs only on mount (when the component appears)
    //   - [a, b], runs on mount *and also* if either `a` or `b` have changed since
    //     the last render
    [isPlaying]
  )

  return <video ref={ref} src={src} loop playsInline />
}
